import React, { useRef, useState } from 'react';

import ParamsInfo from '@/pages/Site/SiteDevice/components/ParamsInfo';
import { deviceManagerControllerDeviceDetail } from '@/services/ess/deviceManager';
import { stationAreaControllerImplShowStationArea as showAreaInfo } from '@/services/ess/stationArea';
import { stationSelfDeviceControllerImplShowStationDevice } from '@/services/ess/stationDevice';
import { useIntl } from '@umijs/max';
import { Divider } from 'antd';
import BaseInfo from './components/BaseInfo';
import TreeList from './components/Tree2';
import Styles from './index.less';

type ParamsInfoObj = {
  baseInfo?: API.DeviceManagerDTO;
  DCInfo?: API.DcInfoDTO;
  ACInfo?: API.AcInfoDTO;
  cellInfo?: API.BatteryCellInfoDTO;
  SysInfo?: API.SystemInfoDTO;
};
const App: React.FC = () => {
  const [baseInfo, setBaseInfo] = useState(null);
  const [fliterTreeData, setfliterTreeData] = useState([]);
  // const [setActiveKey] = useState('1');

  const treeRefs = useRef();
  const [selectedDeviceType, setSelectedDeviceType] = useState();
  const [paramsInfoObj, setParamsInfoObj] = useState();
  const intl = useIntl();

  const fliters = (tree: any, id: number) => {
    return tree
      .map((node: any) => {
        if (node.id === id) {
          return null;
        } else if (node.children && node.children.length) {
          return {
            ...node,
            children: fliters(node.children, id),
          };
        } else {
          return node;
        }
      })
      .filter(Boolean);
  };
  /**
   * 获得参数详情
   * @param values
   */
  const getParamsInfoObj = (values: API.DeviceManagerDTO): ParamsInfoObj => {
    return {
      baseInfo: {
        deviceModel: values?.deviceModel,
        manufacturer: values?.manufacturer,
        bmsNum: values?.bmsNum,
        clusterPerBms: values?.clusterPerBms,
        bmuPerBms: values?.bmuPerBms,
        cellPerBmu: values?.cellPerBmu,
        pictureDir: values?.pictureDir,
        type: values?.type,
        pcsType: values?.pcsType,
        status: values?.status,
      },
      DCInfo: values?.dcInfo,
      ACInfo: values?.acInfo,
      cellInfo: values?.batteryCellInfo,
      SysInfo: values?.systemInfo,
    };
  };
  const treeClick = async (
    device_id: string,
    TreeALL: any,
    deviceType: string | null,
    areaId: string,
  ) => {
    if (device_id) {
      const filteredTree = fliters(TreeALL, device_id);
      setfliterTreeData(filteredTree);
      const res = await stationSelfDeviceControllerImplShowStationDevice({ device_id: device_id });
      if (res.success) {
        setBaseInfo({ ...res.data, deviceType });
        setSelectedDeviceType(deviceType);
        if (res.data.deviceManagerId) {
          const detailRes = await deviceManagerControllerDeviceDetail({
            id: res.data.deviceManagerId,
          });
          setParamsInfoObj(getParamsInfoObj(detailRes.data));
        }
      }
    } else if (areaId) {
      const res = await showAreaInfo({ area_id: areaId });
      if (res.success) {
        setBaseInfo({ ...res.data, deviceType: 'area' });
      }
    }
  };

  const deleteCall = () => {
    setBaseInfo(null);
  };
  /**
   * 获得基础信息
   * @param values
   */
  const getDetailInfo = (values: string | number) => {
    deviceManagerControllerDeviceDetail({
      id: values,
    }).then((res) => {
      setParamsInfoObj(getParamsInfoObj(res.data));
    });
  };
  const handleBaseInfo = (res: boolean) => {
    if (res) {
      treeRefs.current.queryTreeList();
      getDetailInfo(res.deviceManagerId);
    }
  };

  // const items: TabsProps['items'] = [
  //   {
  //     label: intl.formatMessage({ id: 'siteManage.baseInfo' }),
  //     key: '1',
  //   },
  // ];

  return (
    <div className={Styles.OrgWrap}>
      {/*<Tabs*/}
      {/*  items={items}*/}
      {/*  className={Styles.tabs}*/}
      {/*  onChange={(key: string) => {*/}
      {/*    setActiveKey(key);*/}
      {/*  }}*/}
      {/*/>*/}
      <div className={Styles.contentWrap}>
        <div className={Styles.left}>
          <TreeList handleClick={treeClick} deleteCall={deleteCall} ref={treeRefs} />
        </div>
        <div className={Styles.right}>
          <div className={Styles.rightTitle}>
            {intl.formatMessage({ id: 'systemManagement.deviceManagementMenu.deviceManagement' })}
          </div>
          <Divider />
          <div>
            <BaseInfo
              baseInfo={baseInfo}
              handleBaseInfo={handleBaseInfo}
              fliterTreeData={fliterTreeData}
            />
            {(baseInfo?.deviceType === 'PCS' ||
              baseInfo?.deviceType === 'BOX' ||
              baseInfo?.deviceType === 'CABINET') && (
              <ParamsInfo
                selectedDeviceType={selectedDeviceType}
                paramsTotalInfo={paramsInfoObj}
              ></ParamsInfo>
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default App;
